<template>
  <div class="custom">
    <Transfer
      v-model:target-keys="targetKeys"
      :data-source="sourceKeys"
      :titles="['未授权', '已授权']"
      :locale="{ itemUnit: '项', itemsUnit: '项' }"
      listStyle="height:500px; width:1000px"
      @change="handleChange"
      @selectChange="handlerAccount"
    >
      <template #render="item">
        <span class="custom-item">{{ item.title }} </span>
        <Select
          mode="multiple"
          style="width: 230px; float: right"
          :maxTagCount="maxTagCount"
          placeholder="请选择授权角色"
          v-model:value="item.roleIdList"
          @select="selectHandler"
          @deselect="deSelectHandler"
          v-if="item.chosen === true || item.chosen === undefined"
        >
          <SelectOption v-for="options in roleSelectList" v-bind:key="options.id" :value="options.id">
            {{ options.name }}
          </SelectOption>
        </Select>
      </template>
    </Transfer>
  </div>
</template>
<script lang="ts" setup>
import { defineProps, nextTick, ref } from 'vue';
import { Transfer, Select, SelectOption } from 'ant-design-vue';
import { getAppAccount } from '/@/api/system-mgmt/app-mgmt/app';
import { AppUser } from '/@/api/system-mgmt/app-mgmt/model/appModel';
import { useAuthState } from '/@/views/system-mgmt/authorization-mgmt/auth';
import { useUserStore } from '/@/store/modules/user';
import { getRoleList } from '/@/api/authority-mgmt/role';

const maxTagCount = ref(1);

const props = defineProps(['appId', 'subAppId']);
const { setAuthKey, setRoleMap } = useAuthState();
let targetKeys = ref<string[]>([]);
let sourceKeys = ref<AppUser[]>([]);
const userStore = useUserStore();
const tenantCode = userStore.getUserInfo.tenantCode;
let roleId: Map<string, Set<string>> = new Map<string, Set<string>>();
const roleSelectList = ref();
const targetKey = ref();
const frontList = ref([]);

nextTick(async () => {
  if (props.subAppId) {
    roleSelectList.value = await getRoleList({ subAppId: props.subAppId });
  }
});

async function getAuthData() {
  const authDataList = await getAppAccount({
    tenantCode: tenantCode,
    appId: props.appId,
  });
  const keys: string[] = [];
  const mData = [];
  for (let userAuthData of authDataList) {
    const data = {
      key: userAuthData.userId,
      title: userAuthData.userName,
      chosen: userAuthData.isAuth,
      roleIdList: userAuthData.roleIdList,
    };
    if (data.chosen) {
      keys.push(data.key);
      roleId.set(data.key, new Set<string>(data.roleIdList));
    }
    mData.push(data);
  }

  sourceKeys.value = mData;
  targetKeys.value = keys;
  setAuthKey(targetKeys.value);
  setRoleMap(roleId);
}

const handleChange = (targetKey, direction, moveKeys) => {
  moveKeys.forEach((item) => {
    if (direction === 'left') {
      sourceKeys.value.forEach((temp) => {
        if (temp.key === item) {
          temp.chosen = false;
          roleId.delete(item);
          temp.roleIdList = [];
          setRoleMap(roleId);
        }
      });
    } else {
      sourceKeys.value.forEach((temp) => {
        if (temp.key === item) {
          temp.chosen = true;
        }
      });
      targetKeys.value.push(item);
      roleId.set(item, new Set([]));
    }
  });
  setAuthKey(targetKeys.value);
};

const selectHandler = async (value) => {
  if (roleId.get(targetKey.value) !== undefined) {
    let temp = new Set([]);
    roleId.get(targetKey.value).forEach((item) => {
      temp.add(item);
    });
    temp.add(value);
    await roleId.delete(targetKeys.value);
    await roleId.set(targetKey.value, temp);
    setRoleMap(roleId);
  } else {
    roleId.set(targetKey.value, new Set([value]));
    setRoleMap(roleId);
  }
};

const deSelectHandler = async (value) => {
  roleId.get(targetKey.value).delete(value);
  roleId.set(targetKey.value, roleId.get(targetKey.value));
  await setRoleMap(roleId);
};

const handlerAccount = (sourceSelectedKeys, targetSelectedKeys) => {
  if (targetSelectedKeys.length > frontList.value.length) {
    targetKey.value = targetSelectedKeys[targetSelectedKeys.length - 1];
  } else {
    frontList.value.forEach((item) => {
      if (targetSelectedKeys.indexOf(item) === -1) {
        targetKey.value = item;
      }
    });
  }
  frontList.value = targetSelectedKeys;
};

getAuthData();

defineExpose({ getAuthData });
</script>

<style lang="less">
.custom .ant-select-multiple .ant-select-selection-item-remove {
  color: inherit;
  font-style: normal;
  line-height: 0;
  text-align: center;
  text-transform: none;
  vertical-align: -0.125em;
  text-rendering: optimizelegibility;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  display: inline-block;
  color: rgba(0, 0, 0, 0.45);
  font-weight: bold;
  font-size: 10px;
  line-height: inherit;
  cursor: pointer;
  display: none;
}
</style>
